package cn.xuqiudong.blog.module.third.service;

import cn.xuqiudong.blog.constant.GlobalFieldParams;
import cn.xuqiudong.blog.constant.ThirdProperties;
import cn.xuqiudong.common.blog.model.BlogThirdUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author Vic.xu
 * 描述:
 * @since  2020/7/21 0021 17:53
 */
public abstract class AbstractAuthService {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    protected BlogThirdUserService blogThirdUserService;

    @Autowired
    protected ThirdProperties thirdProperties;

    /**
     * oauth 类型
     * @return ThirdTypeEnum
     */
    public abstract GlobalFieldParams.ThirdTypeEnum type();

    /**
     * 通过code获取access_token
     * @param code code
     * @return access_token
     */
    public abstract String getAccessToken(String code);

    /**
     * 根据access_token  获取用户信息
     * @param accessToken accessToken
     * @return BlogThirdUser
     */
    public abstract BlogThirdUser getUserInfo(String accessToken);

    /**
     * 获得配置文件
     * @return ThirdProperties
     */
    public ThirdProperties.ThirdAuthConfig config() {
        ThirdProperties.ThirdAuthConfig config = thirdProperties.getConfigByType(type().name());
        logger.debug("{} config {}", type().name(), config);
        return config;
    }

    /**
     * 根据code获取用户信息，并更新本地数据库，
     * @param code 授权码
     * @return BlogThirdUser
     */
    public BlogThirdUser findUserInfoByCode(String code) {
        String accessToken = getAccessToken(code);
        BlogThirdUser user = getUserInfo(accessToken);
        user = blogThirdUserService.checkUser(user);
        return user;

    }


}
